<template>
	<view class="main" :style="{ bottom: bottom }">
		<!-- 通讯录/消息通知按钮 -->

		<view class="toolbar">
			<view class="" @longpress="handleLongPress" @touchstart="handleTouchStart" @touchend="handleTouchEnd" @touchmove="handleTouchMove">
				<view class="btnbox contact" v-if="currentSession.length > 0 && currentSession[0]">
					<image
						class="img"
						:src="currentSession[0].lastMessage.nicPic.url || '/static/default-avatar.png'"
						mode="aspectFill"
						:alt="currentSession[0].name || '用户头像'"
					/>

					<text class="btntxt">{{ currentSession[0].name || '联系人' }}</text>

					<uni-badge class="uni-badge" :text="formatUnreadCount(currentSession[0].unreadCount)"></uni-badge>
				</view>
			</view>
            <view class="btnbox" v-if="poiShow"  @click.stop="handlePoi" >
            	<image class="img" src="/static/map.png" mode=""></image>
            	<text class="btntxt">POI</text>
            </view>
			<!-- 收藏按钮 -->
			<view class="btnbox" v-if="favoriteShow" @longpress.prevent="handleFavorite" @tap.stop="handerlove">
				<uni-icons :type="isFavorite ? 'star-filled' : 'star'" size="30" color="#ffaa7f"></uni-icons>
				<text class="btntxt">收藏</text>
			</view>

			<view class="btnbox" @click.stop="toCart" v-if="cartShow" >
				<image class="img" src="/static/shoping.png" mode="" alt="购物车"></image>
				<view v-if="cart.items.length > 0" class="uni-badge">
					<text class="uni-badge-txt">{{ cart.items.length }}</text>
				</view>

				<text class="btntxt">购物车</text>
			</view>
			<view class="btnbox chat" @click.stop="toChat" v-if="chatBarShow">
				<uni-icons type="chatboxes-filled" size="30" color="green"></uni-icons>
				<view v-if="storeData.unreadCount > 0" class="uni-badge">
					<text class="uni-badge-txt">{{ storeData.unreadCount }}</text>
				</view>
				<text class="btntxt">聊天</text>
			</view>
			<view class="btnbox" @click.stop="toMap" v-if="mapShow">
				<image class="img" src="/static/map.png" mode=""></image>
				<text class="btntxt">地图</text>
			</view>

			<view class="btnbox" @click.stop="toLocation" v-if="locationTip">
				<uni-icons v-if="isfly" type="location" size="30" color="#55aa00"></uni-icons>
				<image v-if="!isfly" src="/static/walk.png" style="width: 50rpx; height: 50rpx" mode="aspectFill"></image>

				<text class="btntxt">{{ isfly ? '定位' : '随行' }}</text>
			</view>
		</view>
	
	</view>
</template>

<script>
import { getGridCode } from '../utils/getSurroundingGrids.js';
import getIsFavorite from '../utils/getIsFavorite';
import { ceil } from 'lodash-es';
const linli = uniCloud.importObject('linliChat', { customUI: true });
import setToTarget from '../utils/setTarget.js';

export default {
	name: 'RightBar',
	props: {
		group: {
			type: Object,
			default: () => ({})
		},
		bottom: {
			type: String,
			default: '550rpx'
		},
		poiShow:{
			type:Boolean,
			default:false
		},

		cartShow: {
			type: Boolean,
			default: false
		},
		favoriteShow: {
			type: Boolean,
			default: false
		},
		locationTip: {
			type: Boolean,
			default: false
		},
		chatBarShow: {
			type: Boolean,
			default: true
		},
		friendShow: {
			type: Boolean,
			default: true
		},
		ownBarShow: {
			type: Boolean,
			default: true
		},
		mapShow: {
			type: Boolean,
			default: true
		}
	},
	computed: {
		cart() {
			return this.$store.state.cart || { items: [] };
		},
		own() {
			return this.$store.state.msg.own;
		},
		storeData() {
			return this.$store.state.msg || {};
		},

		isfly() {
			return this.$store.state.msg.isFly;
			// return this.$store.getters["msg/isfly"]
		},

		location() {
			return this.storeData.location || {};
		},
		currentSession() {
			return this.$store.getters['msg/currentSession'] || [];
		},
		showFlyButton() {
			const loc1 = getGridCode(this.storeData.location || '');
			const loc2 = getGridCode(this.storeData.senderLocation || '');
			return loc1 != loc2;
		}
	},
	data() {
		return {
			isFavorite: false,
			favorite_id: '',
			isBlinking: true,
			startX: 0,
			startY: 0,
			isMoved: false,
			longPressTimer: null, // 长按计时器
			isLongPressed: false, // 是否触发了长按
			defaultAvatar: '/static/nicPic/m1.png'
		};
	},
	watch: {
		currentSession: {
			handler(newVal, oldVal) {
				if (!Array.isArray(newVal)) return;

				const count = newVal.reduce((sum, item) => {
					const unread = typeof item.unreadCount === 'number' ? item.unreadCount : 0;
					return sum + Math.max(0, unread);
				}, 0);

				// 有未读消息时才闪烁
				this.isBlinking = count > 0;
			},
			deep: true,
			immediate: true
		},
		
		cart:{
			handler(newval){
		
			},immediate:true
		},

		location: {
			async handler(newVal) {
				if (!newVal) return;

				try {
					const res = await getIsFavorite(this.storeData.location || {}, this.storeData.user?.favorite || []);

					this.isFavorite = res.isFavorite;
					this.favorite_id = res.favorite_id || '';
				} catch (error) {
					console.error('获取收藏状态失败:', error);
				}
			},
			deep: true,
			immediate: true
		}
	},
	async mounted() {
		// 组件挂载时初始化数据
		this.initData();
		this.isBlinking = true;
	},
	methods: {
	
		handleRegOwn() {
			uni.navigateTo({
				url: '/pages/regOwn/regOwn'
			});
		},
		navigatorOwn() {
			if (this.own && this.own.ownId !== this.storeData.user.userId) {
				uni.navigateTo({
					url: `/pages/PrivateChat/PrivateChat?id=${this.own.ownId}`
				});
			}
		},
		naviAdim() {
			uni.navigateTo({
				url: `/own/ownAdmin/ownAdmin?groupId=${this.own.groupId}`
			});
		},
		handleTouchStart(e) {
			this.isMoved = false;
			this.isLongPressed = false;
			this.startX = e.touches[0].pageX;
			this.startY = e.touches[0].pageY;

			// 300ms后视为长按（可调整时长）
			this.longPressTimer = setTimeout(() => {
				if (!this.isMoved) {
					this.isLongPressed = true;
					this.handleLongPress(); // 执行长按逻辑
				}
			}, 300);
		},
		handleTouchMove(e) {
			const moveX = Math.abs(e.touches[0].pageX - this.startX);
			const moveY = Math.abs(e.touches[0].pageY - this.startY);

			if (moveX > 5 || moveY > 5) {
				this.isMoved = true;
				clearTimeout(this.longPressTimer); // 滑动时取消长按计时
			}
		},
		handleTouchEnd() {
			clearTimeout(this.longPressTimer); // 清除计时器
			if (!this.isMoved && !this.isLongPressed) {
				this.handleContact(); // 未滑动且未触发长按，执行点击
			}
		},

		async initData() {
			// 初始化收藏状态
			if (this.storeData.location && this.storeData.user?.favorite) {
				try {
					const res = await getIsFavorite(this.storeData.location, this.storeData.user.favorite);
				
					this.isFavorite = res.isFavorite;
					this.favorite_id = res.favorite_id || '';
				} catch (error) {
					console.error('初始化收藏状态失败:', error);
				}
			}
		},

		// 格式化未读数量，超过99显示99+
		formatUnreadCount(count) {
			return count > 99 ? '99+' : count;
		},
		toMap() {
			uni.navigateTo({
				url: '/pages/main/main'
			});
		},
		// 收藏功能处理
		async handleFavorite() {
			// 如果需要直接切换收藏状态而非跳转页面，可以在这里实现
			// 例如: await toggleFavorite(this.favorite_id);

			uni.navigateTo({
				url: `/pages/contacts/contacts?currentTab=收藏`
			});
		},

		// 回当地
		toLocation() {
			this.$store.commit('msg/SET_isFly', false);
			this.$store.commit('msg/SET_location', this.$store.state.msg.senderLocation);
			this.$emit('toLocation');
		},

		// 处理联系人点击
		handleContact() {
			if (this.currentSession.length > 0 && this.currentSession[0]) {
				const user = this.currentSession[0];
				uni.navigateTo({
					url: `/pages/PrivateChat/PrivateChat?id=${user.userId}`
				});
			} else {
				// 无会话时进入通讯录
				uni.switchTab({
					url: '/pages/contacts/contacts'
				});
			}
		},

		// 长按处理
		handleLongPress() {
			uni.switchTab({
				url: '/pages/contacts/contacts'
			});
		},

		// 标为已读
		markAsRead() {
			if (this.currentSession.length > 0 && this.currentSession[0]) {
				// 调用Vuex action更新未读状态
				this.$store.dispatch('msg/updateUnreadCount', {
					userId: this.currentSession[0].userId,
					count: 0
				});
			}
		},
		handlePoi(){
			this.$emit('poiShow')
		},

		// 删除会话
		deleteSession() {
			if (this.currentSession.length > 0 && this.currentSession[0]) {
				// 调用Vuex action删除会话
				this.$store.dispatch('msg/deleteSession', this.currentSession[0].userId);
			}
		},
		toChat() {
	
			setToTarget('public',{targetName:this.storeData.address})
            this.$store.commit('msg/SET_queryParam',{type:'public',location:this.storeData.location})
			uni.navigateTo({
			url: '/pages/messages/messages',
			animationType:'fade-in'
			
			});
		},
		// 前往购物车
		toCart() {
			uni.navigateTo({
					url: '/pages/shopcart/shopcart'
				});
		
		},
		async handerlove() {
		
			let result = {};
			try {
				await uni.showLoading({ title: '处理中...' });
				let name = '';
				if (this.isFavorite) {
					const data = {
						favorite_id: this.favorite_id,
						action: 'remove',
						userId: this.storeData.user.userId,
						type: 'location'
					};
					const res = await uni.showModal({
						title: '确认删除收藏点？',
						content: ''
					});
					console.log(res);
					if (res[1].confirm) {
						result = await linli.favorite(data);
						console.log('删除', result);
						// result=this.storeData.user.favorite.filter(item=>item.favorite_id!==this.favorite_id)
					}
				} else {
					const res = await uni.showModal({
						title: '位置收藏',
						editable: true,
						placeholderText: '请输入位置备注'
					});
					console.log('555', res);
					if (!res[1].confirm) {
						uni.showToast({
							title: '已取消',
							position: 'center'
						});
						return;
					}
					name = res[1].content;
					const data = {
						userId: this.storeData.user.userId,
						favorite_id: this.favorite_id,
						action: 'add',
						type: 'location',
						address: this.storeData.address || '地址不明',
						name: name || '收藏点',
						location: this.storeData.location
					};

					result = await linli.favorite(data);
				}
				console.log('回传的收藏数据', result);
				if (result.code) {
					this.$store.commit('msg/SET_user', { ...this.storeData.user, favorite: result.data.favorite });
					const res = getIsFavorite(this.storeData.location, this.storeData.user.favorite);
					this.$emit('reLoadData');
					this.isFavorite = res.isFavorite;
				} else {
					uni.showToast({
						title:`${result.msg}`,
						icon:'none',
						position:'center',
						duration:3000
					})
					console.error('操作失败');
				}
			} catch (error) {
				console.error('操作失败', error);
				uni.showToast({
					title: '操作失败，请重试',
					icon: 'none',
					duration: 2000
				});
			} finally {
				uni.hideLoading();
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.main {
	position: fixed;
	right: 20rpx;
	z-index: 100;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}
.ownBar {
	display: flex;
	align-items: center;
	padding: 16rpx;
}

.own {
	display: flex;
	flex-direction: column;
	align-items: center;

	transition: transform 0.2s ease;
}
.ownimg {
	width: 100rpx;
	height: 100rpx;
	border-radius: 50%;
    border: 3rpx solid #55aaff;
}
.own:active {
	transform: scale(0.96);
}


.img {
	width: 100%;
	height: 100%;
}

/* 下方圆角标签样式 */
.label {
	margin-top: 16rpx;
	height: 36rpx;
	width: 110rpx;
	border-radius: 20rpx;
	position: relative;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
}

/* 标签文本样式 */
.label-txt {
	font-size: 24rpx;
	color: #fff;
	font-weight: 500;
}

/* 不同状态的标签颜色 */
.owned {
	background-color: #36b37e; /* 绿色 - 已成为管家 */
}

.ownreg {
	background-color: #1890ff; /* 蓝色 - 申请管家 */
}

.img-box {
	background-color: #1890ff;
}
.toolbar {
	display: flex;
	flex-direction: column;
	justify-content: center;
	background-color: #fff;
	box-shadow: 1rpx 1rpx 10rpx rgba(0, 0, 0, 0.2);
 border-radius: 25rpx;
 border: 0.5rpx solid #a6a6a6;
 padding: 5rpx;
	// background-color: #fff;
	// box-shadow: 2rpx 2rpx 10rpx rgba(0, 0, 0, 0.5);
}

.current {
	position: relative;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}
.btnbox {
	display: flex;
	position: relative;
	background-color: #fff;
	flex-direction: column;
	align-items: center;
	margin-bottom: 10rpx;
	justify-content: center;
	border-bottom: 0.5rpx solid #000000;
	transition: transform 0.2s;
	&:active {
		transform: scale(0.95);
	}
}
.contact {
	position: relative;
}

.img {
	width: 55rpx;
	height: 55rpx;
}

.btntxt {
	font-size: 22rpx;
	margin-top: 5rpx;
		/* #ifndef APP-PLUS-NVUE */
		white-space: nowrap;
	/* #endif */
}
.chat {
	position: relative;
}
.uni-badge {
  position: absolute;
  right: 0rpx; /* 调整右侧偏移，避免超出按钮 */
  top: 0rpx; /* 调整顶部偏移，显示在按钮上方 */
  z-index: 999;
   width: 36rpx; /* 最小宽度，确保数字不溢出 */
  height: 36rpx;
  background-color: #ff4444; /* 红色背景，突出显示 */
  border-radius: 50%; /* 圆形角标 */
  display: flex;
  align-items: center;
  justify-content: center;
  }
.uni-badge-txt {
	font-size: 24rpx;
	color: #fff;
	
}

.avatar {
	width: 50rpx;
	height: 50rpx;
	border-radius: 25rpx;
}

.blink {
	animation: blink 1.5s infinite ease-in-out;
	-webkit-animation: blink 1.5s infinite ease-in-out; /* 兼容webkit内核 */
}
@keyframes blink {
	0% {
		transform: scale(1);
		box-shadow: 0 0 0 0 rgba(255, 68, 68, 0.7);
	}
	50% {
		transform: scale(1.05);
		box-shadow: 0 0 0 15rpx rgba(255, 68, 68, 0);
	}
	100% {
		transform: scale(1);
		box-shadow: 0 0 0 0 rgba(255, 68, 68, 0);
	}
}

@-webkit-keyframes blink {
	0% {
		transform: scale(1);
		-webkit-box-shadow: 0 0 0 0 rgba(255, 68, 68, 0.7);
	}
	50% {
		transform: scale(1.05);
		-webkit-box-shadow: 0 0 0 15rpx rgba(255, 68, 68, 0);
	}
	100% {
		transform: scale(1);
		-webkit-box-shadow: 0 0 0 0 rgba(255, 68, 68, 0);
	}
}

// .badge {
// 	position: absolute;
// 	top: -10rpx;
// 	right: 0rpx;
// 	min-width: 36rpx;
// 	height: 36rpx;
// 	z-index: 9999;
// 	padding: 0 8rpx;
// 	background: #ff4444;
// 	color: white;
// 	font-size: 24rpx;
// 	border-radius: 40rpx;
// 	display: flex;
// 	align-items: center;
// 	justify-content: center;
// 	border: 2rpx solid white;
// }
</style>
